package com.example.onlinemarket.controller;

import com.example.onlinemarket.bean.*;
import com.example.onlinemarket.bean.mobile.*;
import com.example.onlinemarket.service.GoodService;
import com.example.onlinemarket.service.OrderItemService;
import com.example.onlinemarket.service.OrderService;
import com.example.onlinemarket.service.UserService;

import com.example.onlinemarket.util.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static com.example.onlinemarket.bean.mobile.MobileGood.getMobileGoodsByCustomer;
import static com.example.onlinemarket.bean.mobile.MobileUser.getShops;
import static com.example.onlinemarket.util.FileUtil.prefixPath;
import static com.example.onlinemarket.util.JSONUtil.toJson;

@RestController
@RequestMapping(value = "/mobile",produces = "text/plain;charset=UTF-8")
public class MobileController {
    private UserService userService;
    private GoodService goodService;
    private OrderService orderService;
    private OrderItemService orderItemService;
    @Autowired
    public void setOrderItemService(OrderItemService orderItemService) { this.orderItemService = orderItemService; }
    @Autowired
    public void setOrderService(OrderService orderService) { this.orderService = orderService; }
    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }
    @Autowired
    public void setGoodService(GoodService goodService) { this.goodService = goodService; }
    private Logger logger;
    @Autowired
    public void setLogger() {logger = LoggerFactory.getLogger(MobileController.class); }

    private final String tempUserImgPath = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\img\\tempUserImg.jpg";

    //根据userName获取对应购物车
    @PostMapping("/shoppingCart")
    public String getShoppingCart(String userId){
        if(userId!=null&&!userId.isEmpty()){
            int id = Integer.parseInt(userId);
            if(orderService.haveShoppingCart(id)){
                List<List<MobileOrderInfo>> orderItemInfos = orderService.getUserOrder(id, "购物车", true);
                return toJson(orderItemInfos);
            }else
                return "NoShoppingCart";
        }
        return null;
    }

    //客户端回传新的购物车数据
    @PostMapping("/uploadShoppingCart")
    public void uploadShoppingCart(String shoppingCart, String isPurchased, String id, String address){
        if((shoppingCart!=null&&!shoppingCart.isEmpty())
        &&(isPurchased!=null&&!isPurchased.isEmpty())
        &&(id!=null&&!id.isEmpty())){
            List<EasyOrderInfo> orderInfoList = JSONUtil.fromJsons(shoppingCart, new TypeReference<List<EasyOrderInfo>>() {});
            if(orderInfoList!=null){
                int userId = Integer.parseInt(id);
                if(orderInfoList.isEmpty()){//当购物车为空时清空购物车
                    List<Order> shoppingOrders = orderService.getShoppingOrders(userId);
                    for(Order order:shoppingOrders){
                        int orderId = order.getOrderId();
                        orderService.delOrderByOrderId(orderId);
                        orderItemService.delOrderItemsByOrderId(orderId);
                    }
                }else{
                    boolean isPurchase = Boolean.parseBoolean(isPurchased);
                    for(EasyOrderInfo info:orderInfoList) {
                        int orderId = info.orderId;
                        orderItemService.updateOrderItemInfos(orderId, info.orderItemInfoList);
                        orderService.updateOrderInfo(orderId, info.note);
                        if (isPurchase) {
                            orderService.updateOrderStatus(orderId, "待发货", address);
                            goodService.updateSellNumAndQuantity(orderId, true);
                        }
                    }
                }
            }
        }
    }

    @PostMapping("/shop")
    public String getShop(String userId){
        if(userId!=null&&!userId.isEmpty()){
            int shopId = Integer.parseInt(userId);
            User shop = userService.getUserById(shopId);
            shop.setPassword("");
            return toJson(new MobileUser(shop));
        }
        return null;
    }

    //获取订单信息
    @PostMapping("/order")
    public String getOrders(String userId, String orderStatus){
        if((userId!=null&&!userId.isEmpty())
        &&(orderStatus!=null&&!orderStatus.isEmpty())){
            int uid = Integer.parseInt(userId);
            return toJson(orderService.getMobileOrders(uid, orderStatus));
        }
        return null;
    }

    //添加鲜花到购物车
    @PostMapping("/addGood")
    public void addGood(String userId, String goodId){
        if((userId!=null&&!userId.isEmpty())
        &&(goodId!=null&&!goodId.isEmpty())){
            int uid = Integer.parseInt(userId);
            int gid = Integer.parseInt(goodId);
            orderService.addShoppingCart(uid, gid);
        }
    }



    //根据传递的userName和password尝试登录
    @GetMapping("/ceshi")
    public String login(){
        System.out.println("测试");
        return "1236456";
    }


    //根据传递的userName和password尝试登录
    @PostMapping("/login")
    public String login(String userName, String password){
        System.out.println("登录账号密码"+userName);
        System.out.println("登录账号密码"+password);
        User user = userService.canUserLogin(userName, userName, password);
        if(user!=null)
            return toJson(new MobileUser(user));
        return "Wrong";
    }

    @PostMapping("/update/user/email")
    public String updateUserEmail(String userName, String email){
        if(userName!=null&&email!=null&&!userName.isEmpty()&&!email.isEmpty()){
            if(userService.updateUserEmail(userName, email))
                return "OK";
            else
                return "ERROR";
        }
        return "ERROR";
    }

    @PostMapping("/update/user/address")
    public String updateUserAddress(String userName, String address){
        if(userName!=null&&address!=null&&!userName.isEmpty()&&!address.isEmpty()){
            if(userService.updateUserAddress(userName, address))
                return "OK";
            else
                return "ERROR";
        }
        return "ERROR";
    }

    @PostMapping("/update/user/password")
    public String updateUserPassword(String userName, String password){
        if(userName!=null&&password!=null&&!userName.isEmpty()&&!password.isEmpty()){
            if(userService.updateUserPassword(userName, password))
                return "OK";
            else
                return "ERROR";
        }
        return "ERROR";
    }

    //根据传递的userName判断是否存在用户名为userName的用户
    @PostMapping("/isUserExists")
    public String isUserExists(String userName){
        return userService.isUserNameExist(userName)?"true":"false";
    }

    //通过传入的信息注册新用户
    @PostMapping("/register")
    public int register(String userName, String password, String email, String address){
        return userService.register(new User(userName, password, email, address, false));
    }

    //查询商店
    @PostMapping("/search/shop")
    public List<MobileUser> searchShop(String searchContent, String recorded, String pageSize){
        if((searchContent!=null&&!searchContent.isEmpty())
        &&(recorded!=null&&!recorded.isEmpty())
        &&pageSize!=null&&!pageSize.isEmpty()){
            searchContent = '%'+searchContent+'%';
            int record = Integer.parseInt(recorded);
            int size = Integer.parseInt(pageSize);
            List<MobileUser> shops = getShops(userService.searchForUser(searchContent, record, size));
            return shops;
        }else return null;
    }

    //获取商铺中鲜花信息
    @PostMapping("/enterShop")
    public List<MobileGood> enterShop(String userId){
        if(userId!=null&&!userId.isEmpty()){
            Integer uid = Integer.parseInt(userId);
            return getMobileGoodsByCustomer(goodService.getUpshelfGoodsByUserId(uid));
        }
        return null;
    }

    @PostMapping("/updatePayPassword")
    public boolean updatePayPassword(String userId, String payPassword){
        System.out.println("账号id"+userId);
        System.out.println("账号密码"+payPassword);
        if((userId!=null&&!userId.isEmpty())&&(payPassword!=null&&!payPassword.isEmpty())){
            System.out.println("账号密码类别1");
            return userService.updatePayPassword(Integer.parseInt(userId), payPassword);

        }else{
            System.out.println("账号密码类别2");
            return false;

        }
    }

    //查询鲜花
    @PostMapping("/search/good")
    public List<MobileGood> searchGood(String searchSpecies, String searchContent, String recorded, String pageSize){
        if((searchContent!=null&&!searchContent.isEmpty())
                &&(searchSpecies!=null&&!searchSpecies.isEmpty())
                &&(recorded!=null&&!recorded.isEmpty())
                &&pageSize!=null&&!pageSize.isEmpty()){
            searchContent = '%'+searchContent+'%';
            int record = Integer.parseInt(recorded);
            int size = Integer.parseInt(pageSize);
            if(searchSpecies.equals("鲜花类型"))
                searchSpecies = "%";
            return getMobileGoodsByCustomer(goodService.searchForUpshelfGood(searchContent, searchSpecies, record ,size));
        }else return null;
    }



//    //陈雪--查询鲜花所有
//    @GetMapping("/search/goodAll")
//    public String searchGoodAll(){
//        return "getMobileGoodsByCustomer(goodService.searchForUpshelfGoodAll())";
//    }
    //陈雪--查询鲜花所有
    @GetMapping("/search/goodAll")
    public List<MobileGood> searchGoodAll(){

        System.out.println("打印商品"+goodService.searchForUpshelfGoodAll());
        return getMobileGoodsByCustomer(goodService.searchForUpshelfGoodAll());
    }




    @PostMapping("/upload")
    public int upload(@RequestParam("uploadfile")MultipartFile file, String userName, String goodId){
        if(file!=null){
            try {
                InputStream in = file.getInputStream();
                if(userName!=null&&!userName.isEmpty())
                    return userService.updateUserImg(userName, in);
                if (goodId!=null&&!goodId.isEmpty())
                    if(goodService.isGoodExist(Integer.parseInt(goodId)))
                        return goodService.updateGoodInfo(goodService.getGoodById(Integer.parseInt(goodId)), in)?1:0;
            } catch (IOException e) { e.printStackTrace(); }
        }
        return -1;
    }

    //下载对应路径为fileName的文件
    @PostMapping("/download")
    public ResponseEntity<FileSystemResource> download(String fileName){
        fileName = fileName.replace("/", "\\");
        File file = new File(prefixPath+fileName);
        if(file.exists()&&file.canRead())
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(new FileSystemResource(file));
        return null;
    }

    @PostMapping({"/refundOrder","/cancelRefundOrder", "/delOrder"})
    public void refundOrder(String orderId){
        if(orderId!=null&&!orderId.isEmpty()){
            int oid = Integer.parseInt(orderId);
            orderService.updateOrder(oid);
        }
    }

    @PostMapping("/signOrder")
    public void signOrder(String orderId){
        if(orderId!=null&&!orderId.isEmpty()){
            int oid = Integer.parseInt(orderId);
            orderService.updateOrder(oid, "已签收");
        }
    }

    @PostMapping("/confirmOrder")
    public void confirmOrder(String orderId){
        if(orderId!=null&&!orderId.isEmpty()){
            int oid = Integer.parseInt(orderId);
            orderService.updateOrder(oid, "已确认");
        }
    }
}
